const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require('koa2-cors')
const { koaBody } = require('koa-body');
const path = require('path')
const login = require('./routes/login')
const auth = require('./utils/auth')
const admin = require('./routes/admin')
const apper = require('./routes/apper')


// error handler
onerror(app)
let num=0
app.use(koaBody({
  multipart: true, //开启文件上传 
  formidable: { // 路径配置
    // 在配置选项option 不推荐使用相对路径
    // uploadDir: path.join(__dirname, './public/image/headimg'),  //配置保存路径
    keepExtensions: true,//保存文件扩展名
    onFileBegin: (name, file) => {
      // 重新定义文件保存路径和文件名
      // 生成新的文件名，并添加时间戳防止重复
      const fileName = `${Date.now()}-${name}${num++}.${file.newFilename.split('.')[1]}`;
      file.newFilename = fileName
      // 修改文件保存路径
      file.filepath = path.join(__dirname, `./public/image/headimg/${fileName}`);
    }
  }
}))
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))

// middlewares
app.use(cors())

app.use(json())
app.use(logger())

app.use(require('koa-static')(__dirname + '/public'))



app.use(views(__dirname + '/views', {
  extension: 'pug'
}))


// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})


// routes
app.use(login.routes(), login.allowedMethods())
app.use(auth)
// routes
app.use(admin.routes(), admin.allowedMethods())
app.use(apper.routes(), apper.allowedMethods())


// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
